package com.cloudsigns.factorymanager2.engineering.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.cloudsigns.factorymanager2.R;
import com.cloudsigns.factorymanager2.cusenum.CommonEnum;
import com.cloudsigns.factorymanager2.engineering.IView.IEngineeringUsersListView;
import com.cloudsigns.factorymanager2.engineering.adapter.AddPublicationOrderAdapter;
import com.cloudsigns.factorymanager2.engineering.adapter.PopWindowAdapter;
import com.cloudsigns.factorymanager2.engineering.bean.Dispatchbean;
import com.cloudsigns.factorymanager2.engineering.bean.MediaBean;
import com.cloudsigns.factorymanager2.engineering.bean.OrderParentBean;
import com.cloudsigns.factorymanager2.engineering.bean.PatrolOrderBean;
import com.cloudsigns.factorymanager2.engineering.bean.UserInfoBean;
import com.cloudsigns.factorymanager2.engineering.customview.SpinerPopWindow;
import com.cloudsigns.factorymanager2.engineering.presenter.EngineeringUserListPresenter;
import com.cloudsigns.factorymanager2.project.myinerface.ItemRemoveListener;
import com.cloudsigns.factorymanager2.project.utils.ConstantUtil;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by tony on 2018/5/19.
 */

public class EditDispatchInfomationForPatrolActivity extends Activity implements View.OnClickListener, IEngineeringUsersListView, AdapterView.OnItemClickListener, ItemRemoveListener {
    private View rl_back;
    private TextView tv_title;
    private RadioGroup rg_associated_size;
    private RadioButton rb_inner_dispatch;
    private View rl_add_product;
    private TextView edt_inner_install_docking_colon, edt_external_dispatch_company, edt_external_install_docking_colon;
    private ScrollView scrollview;
    private LinearLayout ll_region;
    private TextView btn_upload;
    private View ll_inner_install_docking_colon, rl_external_dispatch;
    private ImageView img_inner_right,img_point_locationt;
    private LayoutInflater layoutInflater;
    private String dispatch_way = "内派";
    private CommonEnum.ROLECATEGORY rolecategory;
    private List<UserInfoBean> userInfoBeanList = new ArrayList<UserInfoBean>();
    private List<String> popStrLs = new ArrayList<String>();
    private SpinerPopWindow<String> mSpinerPopWindow;
    private PopWindowAdapter popWindowAdapter;
    private UserInfoBean userInfoBean;
    private PatrolOrderBean patrolOrderBean;
    private final String TAG = EditDispatchInfomationForPatrolActivity.class.getSimpleName();
    private EngineeringUserListPresenter engineeringUserListPresenter;
    //    private List<String> selectedItemList = new ArrayList<String>();
    //    private ArrayList<MediaBean> mediaBeanList = new ArrayList<>();
    HashMap<String, List<MediaBean>> selectedBeanMap = new HashMap<>();
//    private ArrayList<MediaBean> selectedMediaList = new ArrayList<>();


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏
        // 沉浸式状态栏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                    );
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN

                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);

        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        setContentView(R.layout.layout_edit_dispatchinformation_for_patrol);

        engineeringUserListPresenter = new EngineeringUserListPresenter(this);
        layoutInflater = getLayoutInflater();
        init();
        if (null != getIntent()) {
            rolecategory = (CommonEnum.ROLECATEGORY) getIntent().getSerializableExtra(ConstantUtil.KEY_1);
            patrolOrderBean = (PatrolOrderBean) getIntent().getSerializableExtra(ConstantUtil.KEY_2);
//            ArrayList<MediaBean> medialist = (ArrayList<MediaBean>) getIntent().getSerializableExtra("selecteddata");
//            selectedMediaList.addAll(medialist);

//            for (MediaBean mediaBean : medialist) {
//                selectedItemList.add(mediaBean.getId());
//            }

            engineeringUserListPresenter.getUserList(rolecategory);
        }


    }

    private void init() {
        rl_back = findViewById(R.id.rl_back);
        tv_title = findViewById(R.id.tv_title);
        rg_associated_size = findViewById(R.id.rg_associated_size);
        rb_inner_dispatch = findViewById(R.id.rb_inner_dispatch);
        edt_inner_install_docking_colon = findViewById(R.id.edt_inner_install_docking_colon);
        edt_external_dispatch_company = findViewById(R.id.edt_external_dispatch_company);
        edt_external_install_docking_colon = findViewById(R.id.edt_external_install_docking_colon);
        rl_add_product = findViewById(R.id.rl_add_product);
        btn_upload = findViewById(R.id.btn_upload);
        ll_inner_install_docking_colon = findViewById(R.id.ll_inner_install_docking_colon);
        rl_external_dispatch = findViewById(R.id.rl_external_dispatch);
        scrollview = findViewById(R.id.scrollview);
        ll_region = findViewById(R.id.ll_region);
        img_inner_right=findViewById(R.id.img_inner_right);
        img_point_locationt=findViewById(R.id.img_point_locationt);

        tv_title.setText(getResources().getText(R.string.edit_dispatch_information));
        rl_back.setOnClickListener(this);
        btn_upload.setOnClickListener(this);
        img_point_locationt.setOnClickListener(this);
        rb_inner_dispatch.setChecked(true);
        img_inner_right.setOnClickListener(this);

        rg_associated_size.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, @IdRes int id) {
                if (id == R.id.rb_inner_dispatch) {
                    dispatch_way = "内派";
                    showDispatchContent();
                } else if (id == R.id.rb_external_dispatch) {
                    dispatch_way = "外派";
                    showDispatchContent();
                }

            }
        });

        rb_inner_dispatch.setChecked(true);


        mSpinerPopWindow = new SpinerPopWindow<String>(this, this);
        popWindowAdapter = new PopWindowAdapter(this, TAG);
        popWindowAdapter.setData(popStrLs);
        mSpinerPopWindow.setAdapter(popWindowAdapter);
    }

    private void initData() {
        List<MediaBean> mediaBeanList = patrolOrderBean.getMediaList();
        if (null != mediaBeanList) {
            selectedBeanMap.clear();

            for (MediaBean mediaRegionBean : mediaBeanList) {
                CommonEnum.AssignStatus assignStatus = mediaRegionBean.getAssignStatus();
                if (null != assignStatus) {
                    if (assignStatus == CommonEnum.AssignStatus.CREATED || assignStatus == CommonEnum.AssignStatus.EDITED) {
                        if (mediaRegionBean.isChecked() && !mediaRegionBean.isSend()) {
                            String areaName = mediaRegionBean.getAreaName();

                            if (selectedBeanMap.containsKey(areaName)) {
                                selectedBeanMap.get(areaName).add(mediaRegionBean);
                            } else {
                                List<MediaBean> beanList = new ArrayList<>();
                                beanList.add(mediaRegionBean);
                                selectedBeanMap.put(areaName, beanList);

                            }
                        }
                    } else if (assignStatus == CommonEnum.AssignStatus.SEND) {

                    } else if (assignStatus == CommonEnum.AssignStatus.RECEIVED) {

                    } else if (assignStatus == CommonEnum.AssignStatus.RETURNED) {

                    } else if (assignStatus == CommonEnum.AssignStatus.COMPLETED) {

                    }
                }

            }
        }
//        if (null != selectedMediaList) {
//            for (MediaBean mediaRegionBean : selectedMediaList) {
//                String areaName = mediaRegionBean.getAreaName();
//
//                if (selectedBeanMap.containsKey(areaName)) {
//                    selectedBeanMap.get(areaName).add(mediaRegionBean);
//                } else {
//                    List<MediaBean> beanList = new ArrayList<>();
//                    beanList.add(mediaRegionBean);
//                    selectedBeanMap.put(areaName, beanList);
//
//                }
//            }
//        }

        updateUi();
    }


    private void updateUi() {


        if (null != selectedBeanMap && null != ll_region) {
            ll_region.removeAllViews();

            for (Map.Entry<String, List<MediaBean>> entry : selectedBeanMap.entrySet()) {
                View view = layoutInflater.inflate(R.layout.layout_point_location_content, null);
                TextView tv_area_name = view.findViewById(R.id.tv_area_name);
                tv_area_name.setText(entry.getKey());

                ListView lv_media = view.findViewById(R.id.lv_media);

                List<MediaBean> mediaRegionBeanList = entry.getValue();
                AddPublicationOrderAdapter adapter = new AddPublicationOrderAdapter(this, TAG);
//                PointLocationAdapter adapter = new PointLocationAdapter(this, TAG);
                adapter.setData(mediaRegionBeanList);
                adapter.setItemRemoveListener(this);
                lv_media.setAdapter(adapter);
                view.setTag(mediaRegionBeanList);


                ll_region.addView(view);


            }
        }

        scrollview.smoothScrollTo(0, 0);

    }


    private void showDispatchContent() {
        if (dispatch_way.equals("内派")) {
            ll_inner_install_docking_colon.setVisibility(View.VISIBLE);
            rl_external_dispatch.setVisibility(View.GONE);
        } else if (dispatch_way.equals("外派")) {
            ll_inner_install_docking_colon.setVisibility(View.GONE);
            rl_external_dispatch.setVisibility(View.VISIBLE);
        }
    }


    private void upload() {
        if (null == userInfoBean) {
            Toast.makeText(this, "安装对接不能为空！", Toast.LENGTH_SHORT).show();
        } else {
            List<MediaBean> mediaBeanList = patrolOrderBean.getMediaList();
            if (null != mediaBeanList) {
                for (int i = 0; i < mediaBeanList.size(); i++) {
                    MediaBean mediaBean = mediaBeanList.get(i);

                    String cusSsignReceiveOrderId = System.currentTimeMillis() + "";;

                    CommonEnum.AssignStatus assignStatus = mediaBean.getAssignStatus();
                    if (null != assignStatus) {
                        if (assignStatus == CommonEnum.AssignStatus.CREATED || assignStatus == CommonEnum.AssignStatus.EDITED) {
                            if (mediaBean.isChecked() && !mediaBean.isSend()) {

                                mediaBean.setSend(true);
                                mediaBean.setAssignReceiveAccountId(userInfoBean.getId());
                                mediaBean.setAssignReceiveAccountName(userInfoBean.getName());
                                mediaBean.setAssignReceiveOrderId(cusSsignReceiveOrderId);
                            }
                        }
                    }


                }
            }
            Intent mIntent = new Intent();
            mIntent.putExtra(ConstantUtil.KEY_1, patrolOrderBean);
            mIntent.putExtra(ConstantUtil.KEY_2, userInfoBean);
            mIntent.putExtra("dispatch_way", dispatch_way);


            setResult(RESULT_OK, mIntent);
            finish();
        }

//        Toast.makeText(this, "上传成功！", Toast.LENGTH_SHORT).show();


//        Intent mIntent = new Intent();
//        Dispatchbean dispatchbean = new Dispatchbean();
//        dispatchbean.setDispatchType(dispatch_way);
//        if (null != userInfoBean) {
//            dispatchbean.setDispatchUserId(userInfoBean.getId());
//            dispatchbean.setDispatchUserName(userInfoBean.getName());
//        }
//        mIntent.putExtra(ConstantUtil.KEY_1, dispatchbean);
//        mIntent.putExtra(ConstantUtil.KEY_2, selectedBeanMap);
//        mIntent.putExtra("selectedItemList", (Serializable) selectedItemList);
//        mIntent.putExtra("selecteddata", (Serializable) selectedMediaList);
//
//        setResult(ConstantUtil.START_ACTIVITY_KEY_1, mIntent);
//
////        Toast.makeText(this, "上传成功！", Toast.LENGTH_SHORT).show();
//        finish();
    }

    private void showInnerInstallDockingPopWindow() {
        mSpinerPopWindow.setWidth(edt_inner_install_docking_colon.getWidth());
        mSpinerPopWindow.showAsDropDown(edt_inner_install_docking_colon);
    }


    @Override
    public void remove(int positon) {

    }

    @Override
    public void remove(View view) {

        MediaBean bean = (MediaBean) view.getTag();
        int lvPosition = bean.getLvPosition();
        bean.setChecked(false);

        if (lvPosition >= 0 && lvPosition < patrolOrderBean.getMediaList().size()) {
            patrolOrderBean.getMediaList().set(lvPosition, bean);
        }

        initData();

//        String areaName = bean.getAreaName();
//        if (selectedBeanMap.containsKey(areaName)) {
//            selectedBeanMap.get(areaName).remove(bean);
//            if (selectedBeanMap.get(areaName).size() == 0)
//                selectedBeanMap.remove(areaName);
//
//            selectedItemList.remove(bean.getId());
//            selectedMediaList.remove(bean);
//            updateUi();
//        }


//        CommonEnum.AssignStatus assignStatus = bean.getAssignStatus();
//        if (null != assignStatus) {
//            if (assignStatus == CommonEnum.AssignStatus.CREATED) {
//                String areaName = bean.getAreaName();
//                if (selectedBeanMap.containsKey(areaName)) {
//                    selectedBeanMap.get(areaName).remove(bean);
//                    if (selectedBeanMap.get(areaName).size() == 0)
//                        selectedBeanMap.remove(areaName);
//
//                    selectedItemList.remove(bean.getId());
//                    selectedMediaList.remove(bean);
//                    updateUi();
//                }
//
//            } else if (assignStatus == CommonEnum.AssignStatus.EDITED) {
//                String areaName = bean.getAreaName();
//                if (selectedBeanMap.containsKey(areaName)) {
//                    selectedBeanMap.get(areaName).remove(bean);
//                    if (selectedBeanMap.get(areaName).size() == 0)
//                        selectedBeanMap.remove(areaName);
//
//                    selectedItemList.remove(bean.getId());
//                    selectedMediaList.remove(bean);
//                    updateUi();
//                }
//            } else if (assignStatus == CommonEnum.AssignStatus.SEND) {
//
//            } else if (assignStatus == CommonEnum.AssignStatus.RECEIVED) {
//
//            } else if (assignStatus == CommonEnum.AssignStatus.RETURNED) {
//
//            } else if (assignStatus == CommonEnum.AssignStatus.COMPLETED) {
//
//            }
//    }


    }

    @Override
    public void onClick(View view) {
        TextView tv;
        Intent mIntent;
        switch (view.getId()) {
            case R.id.rl_back:
                finish();
                break;
            case R.id.img_point_locationt:
                mIntent = new Intent(EditDispatchInfomationForPatrolActivity.this, SelectMediaForManagerActivity.class);
//                mIntent.putExtra(ConstantUtil.KEY_1, (Serializable) selectedItemList);
                mIntent.putExtra(ConstantUtil.KEY_2, patrolOrderBean);
//                mIntent.putExtra("selecteddata", selectedMediaList);
                mIntent.putExtra("tag", TAG);
                startActivityForResult(mIntent, ConstantUtil.START_ACTIVITY_KEY_1);
                break;
            case R.id.btn_upload:
                upload();
                break;
            case R.id.img_inner_right:
                showInnerInstallDockingPopWindow();
                break;

        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        edt_inner_install_docking_colon.setText(popStrLs.get(i));
        userInfoBean = userInfoBeanList.get(i);
        mSpinerPopWindow.dismiss();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (requestCode) {
            case ConstantUtil.START_ACTIVITY_KEY_1:
                if (data != null) {
                    patrolOrderBean = (PatrolOrderBean) data.getSerializableExtra(ConstantUtil.KEY_1);
//                    selectedItemList.clear();
//                    selectedMediaList.clear();
//
//                    List<String> ItemList = (List<String>) data.getSerializableExtra(ConstantUtil.KEY_1);
//                    selectedItemList.addAll(ItemList);
//                    ArrayList<MediaBean> beanList = (ArrayList<MediaBean>) data.getSerializableExtra(ConstantUtil.KEY_2);
//                    if (null != beanList) {
//                        for (MediaBean mediaBean : beanList) {
//                            CommonEnum.AssignStatus assignStatus = mediaBean.getAssignStatus();
//                            if (null != assignStatus) {
//                                if (assignStatus == CommonEnum.AssignStatus.CREATED) {
//                                    selectedMediaList.add(mediaBean);
//                                } else if (assignStatus == CommonEnum.AssignStatus.EDITED) {
//                                    selectedMediaList.add(mediaBean);
//                                } else if (assignStatus == CommonEnum.AssignStatus.SEND) {
//
//                                } else if (assignStatus == CommonEnum.AssignStatus.RECEIVED) {
//
//                                } else if (assignStatus == CommonEnum.AssignStatus.RETURNED) {
//
//                                } else if (assignStatus == CommonEnum.AssignStatus.COMPLETED) {
//
//                                }
//                            }
//
//                        }
//                    }
                    initData();

                }
                break;

        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void getDataSuccessed(List<UserInfoBean> dataLs) {
        if (null != dataLs) {
            userInfoBeanList.clear();
            userInfoBeanList.addAll(dataLs);
            for (UserInfoBean userInfoBean : userInfoBeanList) {
                popStrLs.add(userInfoBean.getName() + ":" + userInfoBean.getId());
            }

            popWindowAdapter.setData(popStrLs);
            popWindowAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void showFailedError(String desc) {
        Toast.makeText(this, desc, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mSpinerPopWindow != null) {
            mSpinerPopWindow.dismiss();
            mSpinerPopWindow = null;
        }


    }

}
